package com.maizhi.service.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import com.maizhi.dao.BaseDaoI;
import com.maizhi.httpmodel.EasyuiTreeNode;
import com.maizhi.httpmodel.LigerTreeNode;
import com.maizhi.httpmodel.ResourcesModel;
import com.maizhi.model.Menu;
import com.maizhi.model.Resource;
import com.maizhi.model.RoleResource;
import com.maizhi.service.ResourceServiceI;
import com.maizhi.util.MenuComparator;
import com.maizhi.util.ResourcesComparator;

@Service("resourceService")
public class ResourceServiceImpl extends BaseServiceImpl<Resource> implements
		ResourceServiceI {

	private static final Logger logger = Logger.getLogger(ResourceServiceImpl.class);

	private BaseDaoI<Resource> resourceDao;
	private BaseDaoI<RoleResource> roleResourceDao;

	 

	public BaseDaoI<Resource> getResourceDao() {
		return resourceDao;
	}

	@Autowired
	@Qualifier("resourceDao")
	public void setResourceDao(BaseDaoI<Resource> resourceDao) {
		this.resourceDao = resourceDao;
	}

	public BaseDaoI<RoleResource> getRoleResourceDao() {
		return roleResourceDao;
	}

	@Autowired
	@Qualifier("roleResourceDao")
	public void setRoleResourceDao(BaseDaoI<RoleResource> roleResourceDao) {
		this.roleResourceDao = roleResourceDao;
	}

	@Cacheable(value = "ResourcesCache", key = "'tree'+#id")
	@Transactional(readOnly = true)
	public List<EasyuiTreeNode> tree(String id) {
		String hql = "from Resource t where t.resource is null order by t.seq";
		if (id != null && !id.trim().equals("")) {
			hql = "from Resource t where t.resource.id ='" + id + "' order by t.seq";
		}
		List<Resource> resourceses = resourceDao.find(hql);
		List<EasyuiTreeNode> tree = new ArrayList<EasyuiTreeNode>();
		for (Resource syresources : resourceses) {
			tree.add(tree(syresources, false));
		}
		return tree;
	}

	private EasyuiTreeNode tree(Resource syresources, boolean recursive) {
		EasyuiTreeNode node = new EasyuiTreeNode();
		node.setId(syresources.getId());
		node.setText(syresources.getText());
		Map<String, Object> attributes = new HashMap<String, Object>();
		attributes.put("src", syresources.getSrc());
		node.setAttributes(attributes);
		if (syresources.getResources() != null && syresources.getRoleResources().size() > 0) {
			node.setState("closed");
			if (recursive) {// 递归查询子节点
				List<Resource> syresourcesList = new ArrayList<Resource>(syresources.getResources());
				Collections.sort(syresourcesList, new ResourcesComparator());// 排序
				List<EasyuiTreeNode> children = new ArrayList<EasyuiTreeNode>();
				for (Resource r : syresourcesList) {
					EasyuiTreeNode t = tree(r, true);
					children.add(t);
				}
				node.setChildren(children);
			}
		}
		return node;
	}

	@Cacheable(value = "ResourcesCache", key = "'treegrid'+#id")
	@Transactional(readOnly = true)
	public List<ResourcesModel> treegrid(String id) {
		List<ResourcesModel> treegrid = new ArrayList<ResourcesModel>();
		String hql = "from Resource t where t.resource is null order by t.seq";
		if (id != null && !id.trim().equals("")) {
			hql = "from Resource t where t.resource.id = '" + id + "' order by t.seq";
		}
		List<Resource> syresourceses = resourceDao.find(hql);
		for (Resource syresources : syresourceses) {
			ResourcesModel r = new ResourcesModel();
			BeanUtils.copyProperties(syresources, r);
			if (syresources.getResource() != null) {
				r.setParentId(syresources.getResource().getId());
				r.setParentText(syresources.getResource().getText());
			}
			if (syresources.getResources() != null && syresources.getResources().size() > 0) {
				r.setState("closed");
			}
			treegrid.add(r);
		}
		return treegrid;
	}

	@CacheEvict(value = "ResourcesCache", allEntries = true)
	public ResourcesModel add(ResourcesModel resources) {
		Resource syresources = new Resource();
		BeanUtils.copyProperties(resources, syresources);
		if (resources.getParentId() != null && !resources.getParentId().trim().equals("")) {
			syresources.setResource(resourceDao.load(Resource.class, resources.getParentId()));
		}
		resourceDao.save(syresources);
		return resources;
	}

	@CacheEvict(value = "ResourcesCache", allEntries = true)
	public void del(ResourcesModel resources) {
		Resource syresources = resourceDao.get(Resource.class, resources.getId());
		if (resources != null) {
			recursiveDelete(syresources);
		}
	}

	private void recursiveDelete(Resource syresources) {
		if (syresources.getRoleResources() != null && syresources.getRoleResources().size() > 0) {
			Set<Resource> syresourceses = syresources.getResources();
			for (Resource t : syresourceses) {
				recursiveDelete(t);
			}
		}

		List<RoleResource> syroleSyresourcesList = roleResourceDao.find("from RoleResource t where t.resource=?", syresources);
		if (syroleSyresourcesList != null) {// 删除资源前,需要现将角色资源关系表中的相关记录删除
			for (RoleResource syroleSyresources : syroleSyresourcesList) {
				roleResourceDao.delete(syroleSyresources);
			}
		}

		resourceDao.delete(syresources);
	}

	@CacheEvict(value = "ResourcesCache", allEntries = true)
	public ResourcesModel edit(ResourcesModel resources) {
		Resource syresources = resourceDao.get(Resource.class, resources.getId());
		if (syresources != null) {
			BeanUtils.copyProperties(resources, syresources);
			if (!syresources.getId().equals("0")) {// 跟节点不可以修改上级节点
				syresources.setResource(resourceDao.get(Resource.class, resources.getParentId()));
			}
		}
		return resources;
	}
 
	public List<LigerTreeNode> ligerTree() {
		UserServiceImpl us = new UserServiceImpl();
		List<Resource> list = resourceDao.find("SELECT t FROM Resource t,RoleResource r,UserRole u where u.user.id='"+us.loginUser().getId()+"' and u.role.id=r.role.id and r.resourcesId=t.id and t.resource is null and t.isMenu='1'");
		List<LigerTreeNode> tree = new ArrayList<LigerTreeNode>();
		for (Resource res : list) {
			tree.add(ligerTree(res, true));
		}
		return tree;
	}
	
	
	public LigerTreeNode ligerTree(Resource res, boolean recursive) {
		LigerTreeNode node = new LigerTreeNode();
		node.setId(res.getId());
		node.setText(res.getText());
		node.setUrl(res.getSrc());
		if ( res.getResources()!= null && res.getResources().size() > 0) {
			node.setIsexpand(false);
			if (recursive) {// 递归查询子节点
				List<Resource> ress = new ArrayList<Resource>(res.getResources());
				Collections.sort(ress, new ResourcesComparator());// 排序
				List<LigerTreeNode> children = new ArrayList<LigerTreeNode>();
				for (Resource r : ress) {
					if(r.getIsMenu().equals("1")){
						LigerTreeNode t = ligerTree(r, true);
						children.add(t);
					}
				}
				if(children.size()>0){
					node.setChildren(children);
				}
			}
		}
		return node;
	}


}
